import React, { useEffect, useState } from 'react';
import { Spin, Select, DatePicker } from 'antd';
import moment from 'moment';
import type { Moment } from 'moment';
import { TRDefault } from '@/components/index.js';
// @ts-ignore
import { CaretDownOutlined } from '#/utils/antdIcons';
import { RadioGroup } from '../../../components';
import { PriceDiffCurveEcharts } from '../../../components/Charts/index.js';
import type {
  IPostQueryPriceDiffCurveParamsType,
  IPriceDiffCurveDataType,
  IFormValue,
  IPriceDiffCurveType,
} from '../../../type';
import { ISourceType, IValueType, IBaseValueType, ICorrectionType } from '../../../type';
import {
  baseValueOptions,
  correctionOptions,
  sourceOptions,
  valueOptions,
  sourceDefaultOptions,
  sourceDefaultSDOptions,
  sourceTypeSpecialProvinceIds,
} from '../../../dictionary';
import styles from './index.less';
interface IProps {
  /**
   * 请求数据
   */
  formValue?: IFormValue;
  /**
   * lodaing
   */
  loading?: boolean;
  /**
   * error
   */
  error?: boolean;
  /**
   * 数据
   */
  data?: IPriceDiffCurveDataType;
  /**
   * 请求参数
   */
  priceDiffCurveparams?: IPostQueryPriceDiffCurveParamsType;
  /**
   * setPriceDiffCurveparams
   */
  setPriceDiffCurveparams: (params: IPostQueryPriceDiffCurveParamsType) => void;
  /**
   * 请求数据
   */
  onSearch?: (params: IPostQueryPriceDiffCurveParamsType) => void;
}
type RangeValue = [Moment | null, Moment | null] | null;
const dateFormat = 'YYYY/MM/DD';
const PriceDiffCurve = (props: IProps) => {
  const {
    loading,
    error,
    data,
    priceDiffCurveparams,
    formValue,
    onSearch,
    setPriceDiffCurveparams,
  } = props;
  const [queryParams, setQueryParams] = useState<IPostQueryPriceDiffCurveParamsType>({});
  const [values, setValues] = useState<IPriceDiffCurveType>();
  const {
    sourceType = ISourceType.HISTORY,
    valueType = IValueType.MEAN_VALUE,
    baseValue = IBaseValueType.NO_BASE,
    correction = ICorrectionType.AFTER,
    startDate = moment().subtract(7, 'day').format('YYYY-MM-DD'),
    endDate = moment().subtract(1, 'day').format('YYYY-MM-DD'),
    calendarDate,
    provinceId,
    stationId,
  } = queryParams;
  // const date: [moment.Moment, moment.Moment] = [moment(startDate), moment(endDate)];
  // const [lastDates, setLastDate] = useState<RangeValue>([moment(startDate), moment(endDate)]);
  const [dates, setDate] = useState<RangeValue>([moment(startDate), moment(endDate)]);
  useEffect(() => {
    if (priceDiffCurveparams) {
      setQueryParams(priceDiffCurveparams);
      if (
        priceDiffCurveparams.provinceId === '14' &&
        priceDiffCurveparams.sourceType === ISourceType.TIAN_JI
      ) {
        const _values = data?.newChartData;
        setValues(_values);
      } else if (
        priceDiffCurveparams.provinceId === '37' &&
        priceDiffCurveparams.sourceType === ISourceType.TIAN_JI
      ) {
        const _values = data?.newChartData;
        setValues(_values);
      } else {
        const _values: IPriceDiffCurveType | undefined =
          priceDiffCurveparams?.baseValue === IBaseValueType.BASE
            ? priceDiffCurveparams?.correction === ICorrectionType.BEFORE
              ? data?.baseBefore
              : data?.baseAfter
            : priceDiffCurveparams?.correction === ICorrectionType.BEFORE
            ? data?.noBaseBefore
            : data?.noBaseAfter;
        setValues(_values);
      }
    }
  }, [priceDiffCurveparams, data]);

  // 修改预测源
  const _onChangeSourceType = (e: ISourceType) => {
    let _priceDiffCurveparams: IPostQueryPriceDiffCurveParamsType = {
      calendarDate,
      provinceId,
      stationId,
      sourceType: e,
      baseValue: IBaseValueType.NO_BASE,
      correction: ICorrectionType.AFTER,
    };
    if (e === ISourceType.HISTORY) {
      _priceDiffCurveparams = {
        ..._priceDiffCurveparams,
        startDate: moment().subtract(7, 'day').format('YYYY-MM-DD'),
        endDate: moment().subtract(1, 'day').format('YYYY-MM-DD'),
        valueType: IValueType.MEAN_VALUE,
      };
      setDate([moment().subtract(7, 'day'), moment().subtract(1, 'day')]);
    } else {
      _priceDiffCurveparams = {
        ..._priceDiffCurveparams,
        startDate: moment(calendarDate).format('YYYY-MM-DD'),
        endDate: moment(calendarDate).format('YYYY-MM-DD'),
      };
    }
    setQueryParams(_priceDiffCurveparams);
    onSearch && onSearch(_priceDiffCurveparams);
  };

  // 改变统计口径
  const _onChangeValueType = (e: IValueType) => {
    const _priceDiffCurveparams: IPostQueryPriceDiffCurveParamsType = {
      ...queryParams,
      valueType: e,
    };
    setQueryParams(_priceDiffCurveparams);
    onSearch && onSearch(_priceDiffCurveparams);
  };

  // 改变日期
  const _onChangeDate = (e: [moment.Moment, moment.Moment]) => {
    if (!!e) {
      const startDate = moment(e[0]).format('YYYY-MM-DD');
      const endDate = moment(e[1]).format('YYYY-MM-DD');
      const _priceDiffCurveparams: IPostQueryPriceDiffCurveParamsType = {
        ...queryParams,
        startDate,
        endDate,
      };
      setQueryParams(_priceDiffCurveparams);
      onSearch && onSearch(_priceDiffCurveparams);
    }
    setDate(e);
  };
  const disabledDate = (current: Moment) => {
    if (!dates || provinceId != '14') {
      return false;
    }
    if (queryParams.baseValue === 0) {
      return false;
    }
    // let monthDtare
    const tooLate = dates[0] && current.diff(dates[0], 'month') > 0;
    const tooEarly = dates[1] && dates[1].diff(current, 'month') > 0;
    return !!tooEarly || !!tooLate;
  };
  // 改变交易模式
  const _onChangeBaseValue = (e: IBaseValueType) => {
    if (provinceId == '14' && data?.startDate && queryParams.startDate != data?.startDate) {
      setDate([
        moment(e == 1 ? data.startDate : queryParams.startDate),
        moment(data.endDate || queryParams.endDate),
      ]);
    }
    const _priceDiffCurveparams: IPostQueryPriceDiffCurveParamsType = {
      ...queryParams,
      baseValue: e,
    };
    setQueryParams(_priceDiffCurveparams);
    const _values: IPriceDiffCurveType | undefined =
      _priceDiffCurveparams?.baseValue === IBaseValueType.BASE
        ? _priceDiffCurveparams?.correction === ICorrectionType.BEFORE
          ? data?.baseBefore
          : data?.baseAfter
        : _priceDiffCurveparams?.correction === ICorrectionType.BEFORE
        ? data?.noBaseBefore
        : data?.noBaseAfter;
    setValues(_values);
    setPriceDiffCurveparams(_priceDiffCurveparams);
  };

  // 改变控制价格口径
  const _onChangeCorrection = (e: ICorrectionType) => {
    const _priceDiffCurveparams: IPostQueryPriceDiffCurveParamsType = {
      ...queryParams,
      correction: e,
    };
    setQueryParams(_priceDiffCurveparams);
    const _values: IPriceDiffCurveType | undefined =
      _priceDiffCurveparams?.baseValue === IBaseValueType.BASE
        ? _priceDiffCurveparams?.correction === ICorrectionType.BEFORE
          ? data?.baseBefore
          : data?.baseAfter
        : _priceDiffCurveparams?.correction === ICorrectionType.BEFORE
        ? data?.noBaseBefore
        : data?.noBaseAfter;
    setValues(_values);
    setPriceDiffCurveparams(_priceDiffCurveparams);
  };

  return (
    <div className={styles.container}>
      <div className={styles.header}>
        <div className={styles.left}>
          <div className={styles.title}>价差-</div>
          <div className={styles.select}>
            {formValue?.provinceId === '37' ? (
              <Select
                value={sourceType}
                options={sourceDefaultSDOptions as any}
                suffixIcon={<CaretDownOutlined />}
                bordered={false}
                onChange={_onChangeSourceType}
              />
            ) : (
              <Select
                value={sourceType}
                options={
                  formValue?.provinceId &&
                  sourceTypeSpecialProvinceIds.includes(formValue.provinceId)
                    ? sourceOptions
                    : (sourceDefaultOptions as any)
                }
                suffixIcon={<CaretDownOutlined />}
                bordered={false}
                onChange={_onChangeSourceType}
              />
            )}
          </div>
          {/* {sourceType === 'tianji' && priceDiffCurveparams?.baseValueText !== '-1' && (
            <div base-type={priceDiffCurveparams?.baseValueText} className={styles.baseVlaue}>
              {priceDiffCurveparams?.baseValueText === '1'
                ? '有基数'
                : priceDiffCurveparams?.baseValueText === '0'
                ? '无基数'
                : '未知'}
            </div>
          )} */}
        </div>
        <div className={styles.right}>
          {sourceType === ISourceType.HISTORY && (
            <div className={styles.valueType}>
              <Select
                value={valueType as any}
                options={valueOptions as any}
                onChange={_onChangeValueType}
              />
            </div>
          )}
          {sourceType === ISourceType.HISTORY && (
            <div className={styles.date}>
              <DatePicker.RangePicker
                format="YYYYMMDD"
                value={dates}
                disabledDate={disabledDate as any}
                placeholder={['请选择', '请选择']}
                className={styles.datePicker}
                onChange={_onChangeDate as any}
                separator={'-'}
              />
            </div>
          )}
          {/* {provinceId === '14' && (
            <div className={styles.baseValue}>
              <RadioGroup
                value={baseValue}
                options={baseValueOptions}
                onChange={_onChangeBaseValue}
                defaultValue={IBaseValueType.NO_BASE}
              />
            </div>
          )} */}
          {provinceId !== '14' && (
            <div className={styles.correction}>
              <RadioGroup
                value={correction}
                defaultValue={ICorrectionType.AFTER}
                options={correctionOptions}
                onChange={_onChangeCorrection}
              />
            </div>
          )}
        </div>
      </div>
      <div className={styles.content}>
        {loading ? (
          <Spin />
        ) : error ? (
          <TRDefault type={'error'} message={'系统异常'} />
        ) : values ? (
          <div className={styles.charts}>
            <PriceDiffCurveEcharts
              data={values}
              date={formValue?.calendarDate}
              type={queryParams?.baseValue}
            />
          </div>
        ) : (
          <TRDefault type={'emptysm'} message={'暂无数据'} />
        )}
      </div>
    </div>
  );
};

export default PriceDiffCurve;
